﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Reflection;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing.Drawing2D;
using System.Windows.Forms.VisualStyles;

namespace LED_Editor.Controls
{

    public class TrackDataGridViewCell : DataGridViewCell
    {
        public TrackDataGridViewCell()
            : base()
        {
            _rect = new List<Rectangle>();
           // this.ToolTipText = DateTime.Now.Ticks.ToString ();  
        }

        private bool _dataGridViewEventsSet;
        protected override void OnDataGridViewChanged()
        {
            base.OnDataGridViewChanged();
            if (this.DataGridView != null && !_dataGridViewEventsSet)
            {
                DataGridView.MouseDown += new MouseEventHandler(DataGridView_MouseDown);
                DataGridView.MouseMove += new MouseEventHandler(DataGridView_MouseMove);
                DataGridView.MouseUp += new MouseEventHandler(DataGridView_MouseUp);
                _dataGridViewEventsSet = true;
            }
        }

        private TrackDataGridViewColumn _Column
        {
            get
            {
                return (TrackDataGridViewColumn)OwningColumn;
            }
        }

        public override bool Selected
        {
            get
            {
                return false;
            }
            set
            {
                base.Selected = false;
            }
        }

        public override bool ReadOnly
        {
            get
            {
                return false;
            }
            set
            {
                base.ReadOnly = false;
            }
        }

        void DataGridView_MouseUp(object sender, MouseEventArgs e)
        {
            _dataGridViewInitialMoveX = 0;
            _isRightSplitterClicked = false;
            ((DataGridView)sender).Cursor = Cursors.Default;
        }

        int _dataGridViewInitialMoveX;
        int _dataGridViewCurrentMoveX;


        void DataGridView_MouseMove(object sender, MouseEventArgs e)
        {
            if (_isRightSplitterClicked)
            {
                object current = _BindingList[_movingFrameIndex];
                int currentWidth = _rect[_movingFrameIndex].Width; //GetValue<int>(current, "Duration");
                Point screenPoint = e.Location; //this.PointToScreen(e.Location);
                if (_dataGridViewCurrentMoveX == screenPoint.X)
                    return;

                _dataGridViewCurrentMoveX = screenPoint.X;

                int delta = _dataGridViewCurrentMoveX - _dataGridViewInitialMoveX;
                int zoomedDelta = delta;//GetScaledWidth(delta) ;

                int preCalculatedWidth = _initialWidth + (zoomedDelta);
                if (preCalculatedWidth == currentWidth || preCalculatedWidth < 0)
                    return;

                SetWidthCore(_movingFrameIndex, preCalculatedWidth);
                RaiseSelectedFrameChanged(current);
                ((DataGridView)sender).InvalidateCell(this);
                assignWidthCount += 1;

                Point point = e.Location;
                point.Offset(10, 20);
                float sec = GetValue<int>(current, "FrameDuration")/100f;
                this._Column.ToolTip.Show(string.Format("{0:f2}s",sec) , (DataGridView)sender, point, 1000);
                //label1.Text = string.Format("{5}| Width:{0}, Left:{1}, X1:{2}, X2:{3}, Delta:{4}", this.Width, this.Left, screenPoint.X, _initialRightSplitterScreenCoordinatesX, screenPoint.X - _initialRightSplitterScreenCoordinatesX, assignWidthCount);
#if DEBUG
                //string info = string.Format("Init:{0},Delta:{1},ZoomedDelta:{2}", _initialWidth, delta, zoomedDelta);
                //Debug.WriteLine(info);
#endif

            }
        }

        void DataGridView_MouseDown(object sender, MouseEventArgs e)
        {
            _dataGridViewInitialMoveX = e.Location.X;
            DataGridView.HitTestInfo hti = ((DataGridView)sender).HitTest(e.X, e.Y);
            _selectedFrameIndex = -1;

            switch (hti.Type )
            {
                case DataGridViewHitTestType.Cell:
                    break;
                case DataGridViewHitTestType.ColumnHeader:
                    break;
                case DataGridViewHitTestType.HorizontalScrollBar:
                    break;
                case DataGridViewHitTestType.None:
                    RaiseSelectedFrameChanged(null);
                    break;
                case DataGridViewHitTestType.RowHeader:
                    break;
                case DataGridViewHitTestType.TopLeftHeader:
                    break;
                case DataGridViewHitTestType.VerticalScrollBar:
                    break;
                default:
                    break;
            }
            ((DataGridView)sender).InvalidateColumn(_Column.Index);
        }

        public override Type FormattedValueType
        {
            get
            {
                return typeof(object);
            }
        }

        private static Dictionary<string, PropertyInfo> _properties = new Dictionary<string, PropertyInfo>();
 
        private void SetValue(object obj, string propertyName, object value)
        {
            PropertyInfo destProperty = GetPropertyInfo(obj, propertyName);
            destProperty.SetValue(obj, value, null);
        }

        protected override object GetValue(int rowIndex)
        {
           // this.DataGridView.Rows[0].DataBoundItem    OwningRow.Index  
           // DataGridView.Rows.SharedRow(rowIndex);
           // if (rowIndex < 0)
           //     return null;
            return base.GetValue(rowIndex);
        }

        private static PropertyInfo GetPropertyInfo(object obj, string propertyName)
        {
            PropertyInfo destProperty = null;

            _properties.TryGetValue(propertyName, out destProperty);
            if (destProperty == null)
            {
                destProperty = obj.GetType().GetProperty(propertyName);
                _properties.Add(propertyName, destProperty);
            }
            return destProperty;
        }
        private T GetValue<T>(object obj, string propertyName)
        {
            PropertyInfo destProperty = GetPropertyInfo(obj, propertyName);
            return (T)destProperty.GetValue(obj, null);
        }

        private void RecalculateRectangles(IList data,Size size1)
        {
            IList items = data;//_DataManager.List;  
            if (items == null)
                return;

            if (items.Count != _rect.Count)
            {
                //   throw new InvalidOperationException();
                _rect.Clear();

                for (int i = 0; i < items.Count; i++)
                {
                    _rect.Add(new Rectangle());
                }
            }

            for (int i = 0; i < items.Count; i++)
            {
                object currentObject = items[i];
                Rectangle currentRect = _rect[i];



                int currentDuration = GetValue<int>(currentObject, _Column.Duration);
                int zoomedDuration = GetScaledWidth(currentDuration);
                Size size = new Size(zoomedDuration, size1.Height - 4);
                if (i == 0)
                {
                    _rect[i] = new Rectangle(Point.Empty, size);
                }
                else
                {
                    _rect[i] = new Rectangle(currentRect.Location, size);
                }

            }
            for (int i = 0; i < _rect.Count - 1; i++)
            {
                Rectangle previous = _rect[i];
                Rectangle next = _rect[i + 1];

                _rect[i + 1] = new Rectangle(previous.X + previous.Width + 1, 0, next.Width - 1, next.Height);

            }
        }


        private void RecalculateRectangles()
        {
            IList items = _BindingList;//_DataManager.List;  
            if (items == null)
                return;

            if (items.Count != _rect.Count)
            {
                //   throw new InvalidOperationException();
                _rect.Clear();
               
                for (int i = 0; i < items.Count; i++)
                {
                    _rect.Add(new Rectangle());
                }
            }

            for (int i = 0; i < items.Count; i++)
            {
                object currentObject = items[i];
                Rectangle currentRect = _rect[i];

                

                int currentDuration = GetValue<int>(currentObject, _Column.Duration  );
                int zoomedDuration = GetScaledWidth(currentDuration);
                Size size =  new Size(zoomedDuration, Size.Height-4    );
                if (i == 0)
                {
                    _rect[i] = new Rectangle(Point.Empty, size);
                }
                else
                {
                    _rect[i] = new Rectangle(currentRect.Location, size);
                }

            }
            for (int i = 0; i < _rect.Count - 1; i++)
            {
                Rectangle previous = _rect[i];
                Rectangle next = _rect[i + 1];

                _rect[i + 1] = new Rectangle(previous.X + previous.Width+1, 0, next.Width-1, next.Height);

            }
        }

        //private IBindingList _bindingList;
        private bool _listChangedConnected;



        public IBindingList _BindingList
        {
            get
            {
                //RowIndex = 1;// _Column. 
                //if (OwningRow.Index < 0)
                //    return new BindingList<object>() ;   
               // if (Value == null)
               //     return null;

                // if (_value2 == null)
               //     return null;

                IBindingList bindingList = Value as IBindingList;
                if (bindingList == null)
                    return null;

                if (!_listChangedConnected)
                {
                    ((IBindingList)Value).ListChanged += _dataManager_ListChanged;
                    _listChangedConnected = true;
                }
                return bindingList;
            }
        }


        void _dataManager_PositionChanged(object sender, EventArgs e)
        {
        }

        protected override void OnMouseDoubleClick(DataGridViewCellMouseEventArgs e)
        {
            base.OnMouseDoubleClick(e);
            Point clickPoint = e.Location;

            Rectangle? rect = GetRectangleByMouseX(e.Location.X);
            if (rect == null || !rect.HasValue)
                return;

            int frameIndex = GetRectangleIndexByMouseX(e.X);
            object frame = _BindingList[frameIndex];

            string propName = string.Empty;

            if (clickPoint.X < rect.Value.X + rect.Value.Width / 2)
            {
                propName = "StartColor";
            }
            else
            {
                propName = "EndColor";
            }

            bool result = _Column.OnFrameEditing(frame, propName);
            if (result)
            {
                RaiseSelectedFrameChanged(frame);
            }

        }

        void _dataManager_ListChanged(object sender, System.ComponentModel.ListChangedEventArgs e)
        {
            switch (e.ListChangedType)
            {
                case System.ComponentModel.ListChangedType.ItemAdded:
                    _rect.Add(Rectangle.Empty);
                    SelectLast();
                    break;
                case System.ComponentModel.ListChangedType.ItemChanged:
                    break;
                case System.ComponentModel.ListChangedType.ItemDeleted:
                    _rect.RemoveAt(e.NewIndex);
                    break;
                case System.ComponentModel.ListChangedType.ItemMoved:
                    break;
                case System.ComponentModel.ListChangedType.PropertyDescriptorAdded:
                    break;
                case System.ComponentModel.ListChangedType.PropertyDescriptorChanged:
                    break;
                case System.ComponentModel.ListChangedType.PropertyDescriptorDeleted:
                    break;
                case System.ComponentModel.ListChangedType.Reset:
                    break;
                default:
                    break;
            }
            this.DataGridView.InvalidateCell(this);
        }

        void _dataManager_CurrentChanged(object sender, EventArgs e)
        {
        }

        int _rowIndex2;
        object _value2;


        protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
        {
           // if (_Column.IsMouseMove)
           //     return;
            //if (rowIndex < 0)
            //    graphics.DrawRectangle(Pens.Red, clipBounds);
#if DEBUG
            try
            {
#endif
            base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
            //_rowIndex2 = rowIndex;
            //_value2 = value;
            //TextBoxRenderer.DrawTextBox(graphics, cellBounds, TextBoxState.Normal);

            Rectangle rect = new Rectangle(cellBounds.Location, new Size(cellBounds.Width, cellBounds.Height));

            using (Pen pen = new Pen(Color.White,2 ) )
            {
                graphics.DrawLine(pen, rect.Location, new Point(rect.Location.X + rect.Width, rect.Location.Y));
            }
            
            if ((cellState & DataGridViewElementStates.Selected) == DataGridViewElementStates.Selected  )
            {
                using (Brush brush = new LinearGradientBrush(rect, Color.FromArgb(95, 95, 95), Color.FromArgb(150, 150, 150), 90, false))
                {
                    graphics.FillRectangle(brush, rect);
                }
            }
            else
            {
                using (Brush brush = new LinearGradientBrush(rect, Color.FromArgb(50, 50, 50), Color.FromArgb(30, 30, 30), 90, false))
                {
                    graphics.FillRectangle(brush, rect);
                }
            }
            if (value == null)
                return;

            RecalculateRectangles((IList)value, cellBounds.Size);
            for (int i = 0; i < _rect.Count; i++)
            {
                Rectangle eachRect = _rect[i];
                eachRect.Offset(cellBounds.Location.X/* + _Column.HorizontalScrollingOffset*/, cellBounds.Location.Y+2);

                if (!eachRect.IntersectsWith(clipBounds))
                    continue;
                PaintFrameContent(graphics, eachRect, i, (IList)value);
            }
#if DEBUG
            }
            catch
            {

            }
#endif

        }

        private int GetScaledWidth(int width)
        {
           // return (int)_Column.ScaleFactor * width / _Column.InitialScale  ;
            return ZoomHelper.GetScaledWidth (width, _Column.ScaleFactor); 
        }
        private int GetInitialWidth(int scaledWidth)
        {
           // return (int)(scaledWidth * _Column.InitialScale / _Column.ScaleFactor);
            return ZoomHelper.GetInitialWidth (scaledWidth, _Column.ScaleFactor); 
        }

        private void Scale(ref Rectangle eachRect)
        {
            float factor = _Column.ScaleFactor;
            int width = GetScaledWidth(eachRect.Width);
            eachRect = new Rectangle(eachRect.Location, new Size(width, eachRect.Height));

        }

        int _selectedFrameIndex = -1;

        private void PaintFrameContent(Graphics graphics, Rectangle rect, int index,IList list)
        {
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.SmoothingMode = SmoothingMode.AntiAlias;

            //graphics.InterpolationMode = InterpolationMode.Low;
            //graphics.SmoothingMode = SmoothingMode.HighSpeed ;
            //graphics.CompositingMode = CompositingMode.SourceCopy;
            graphics.CompositingQuality = CompositingQuality.HighSpeed;



            object value = list[index];
            Color startColor = GetValue<Color>(value, "StartColor");
            Color endColor = GetValue<Color>(value, "EndColor");


            if (index == _selectedFrameIndex)
            {
                if (rect.Width != 0)
                {
                    using (Brush brush = new LinearGradientBrush(rect, Color.White, Color.Silver, LinearGradientMode.Vertical))
                    {
                        graphics.FillRectangle(brush, rect);
                    }
                }
            }
            else
            {
                    graphics.FillRectangle(GraphicsCache.Instance.GetCachedBrush(_Column.FrameBackColor), rect);
            }
            int customPadding = rect.Height / 5;

            Point topLeft = new Point(rect.Location.X, rect.Location.Y + customPadding);
            Point bottomLeft = new Point(rect.Location.X, rect.Location.Y + rect.Height - customPadding);

            Point topRight = new Point(rect.Location.X + rect.Width, rect.Location.Y + customPadding);
            Point bottomRight = new Point(rect.Location.X + rect.Width, rect.Location.Y + rect.Height - customPadding);

            if (startColor.ToArgb() != endColor.ToArgb())
            {
                graphics.FillPolygon(GraphicsCache.Instance.GetCachedBrush(startColor), new Point[] { topLeft, topRight, bottomLeft, topLeft });
                graphics.FillPolygon(GraphicsCache.Instance.GetCachedBrush(endColor), new Point[] { bottomLeft, topRight, bottomRight, bottomLeft });
                graphics.DrawLine(GraphicsCache.Instance.BlackPen, bottomLeft, topRight);
            }
            else
            {
                graphics.FillRectangle(GraphicsCache.Instance.GetCachedBrush(startColor), topLeft.X, topLeft.Y, rect.Width, rect.Height - 2 * customPadding);
            }
            graphics.DrawLine(GraphicsCache.Instance.BlackPen, new Point(rect.Location.X + rect.Width, rect.Location.Y), new Point(rect.Location.X + rect.Width, rect.Location.Y + rect.Height));
            graphics.DrawLine(GraphicsCache.Instance.BlackPen, topLeft, topRight);
            graphics.DrawLine(GraphicsCache.Instance.BlackPen, bottomLeft, bottomRight);
        }

        private List<Rectangle> _rect;

        private Rectangle? GetLastRectangle()
        {
            if (_rect == null)
                throw new InvalidOperationException();

            if (_rect.Count == 0)
                return null;
            else
                return _rect[_rect.Count - 1];
        }

        private Rectangle? GetRectangleByMouseX(int mouseX)
        {
            if (_rect == null)
                throw new InvalidOperationException();

            //foreach (Rectangle eachRect in _rect)
            //{
            //    if (mouseX >= eachRect.X && mouseX <= eachRect.X + eachRect.Width)
            //        return eachRect;
            //}
            int index = GetRectangleIndexByMouseX(mouseX);
            if (index < 0)
                return null;
            else
                return _rect[index];
        }

        private int GetRectangleIndexByMouseX(int mouseX)
        {
            if (_rect == null)
                throw new InvalidOperationException();
            Rectangle eachRect = Rectangle.Empty;
            for (int i = 0; i < _rect.Count; i++)
            //foreach (Rectangle eachRect in _rect)
            {
                eachRect = _rect[i];
                if (mouseX >= eachRect.X && mouseX <= eachRect.X + eachRect.Width)
                    return i;
            }

            return -1;
        }


        //protected override void OnPaint(PaintEventArgs pe)
        //{
        //    base.OnPaint(pe);
        //    foreach (Rectangle eachRect in _rect)
        //    {

        //        pe.Graphics.FillRectangle(Brushes.WhiteSmoke, eachRect);
        //    }
        //}

        protected override void OnMouseMove(DataGridViewCellMouseEventArgs e)
        {
            base.OnMouseMove(e);
            int index = GetRectangleIndexByMouseX(e.X);
            Rectangle? current = GetRectangleByMouseX(e.X);
            if (current == null || !current.HasValue)
            {
                this.DataGridView.Cursor = Cursors.Default;
                return;
            }
            if (e.X > current.Value.X + current.Value.Width - 10 && e.X < current.Value.X + current.Value.Width)
            {
                this.DataGridView.Cursor = Cursors.SizeWE;
            }
            else
            {
                this.DataGridView.Cursor = Cursors.Hand ;
            }

            //if (_isRightSplitterClicked)
            //{
            //    Point screenPoint = e.Location; //this.PointToScreen(e.Location);
            //    if (_currentRightSplitterScreenCoordinatesX == screenPoint.X)
            //        return;

            //    _currentRightSplitterScreenCoordinatesX = screenPoint.X;

            //    int preCalculatedWidth = _initialWidth + (_currentRightSplitterScreenCoordinatesX - _initialRightSplitterScreenCoordinatesX);
            //    if (preCalculatedWidth == current.Value.Width || preCalculatedWidth < 0)
            //        return;
            //    //Rectangle newRect= new Rectangle(current.Value.Location, new Size(preCalculatedWidth,current.Value.Height ));
            //    SetWidthCore(index, preCalculatedWidth);
            //    this.DataGridView.InvalidateCell(this);
            //    //base.DataGridView.InvalidateCell(e.ColumnIndex, e.RowIndex);
            //    assignWidthCount += 1;
            //    //label1.Text = string.Format("{5}| Width:{0}, Left:{1}, X1:{2}, X2:{3}, Delta:{4}", this.Width, this.Left, screenPoint.X, _initialRightSplitterScreenCoordinatesX, screenPoint.X - _initialRightSplitterScreenCoordinatesX, assignWidthCount);
            //}

        }


        private void SetWidthCore(int index, int width)
        {
            //_rect[index] = newRectangle;
            object frame = _BindingList[index];
            if (frame == null)
                throw new InvalidOperationException("No Frame found at index "+index);

            int zoomedDelta = GetInitialWidth(width);
            SetValue(frame, _Column.Duration  , zoomedDelta);
            //RecalculateRectangles(_BindingList, index);


        }
        bool _isRightSplitterClicked;
        int _initialRightSplitterScreenCoordinatesX;
        int _initialWidth;
        int assignWidthCount = 0;

        int _currentRightSplitterScreenCoordinatesX;

        int _movingFrameIndex;

        private void RaiseSelectedFrameChanged(object frame)
        {
            _Column.OnSelectedFrameChanged(frame);
        }

        protected override bool MouseClickUnsharesRow(DataGridViewCellMouseEventArgs e)
        {
            return base.MouseClickUnsharesRow(e);
        }

        protected override void OnEnter(int rowIndex, bool throughMouseClick)
        {
         /*   base.OnEnter(rowIndex, throughMouseClick);
            Point e = DataGridView.MousePosition;
            //OwningRow.Index = rowIndex;
            _movingFrameIndex = GetRectangleIndexByMouseX(e.X);
            _selectedFrameIndex = _movingFrameIndex;
            // if (currentMovingIndex != _movingFrameIndex)
            // {
            object frame = null;//DataGridView.Rows[e.RowIndex].DataBoundItem; 

            if (_movingFrameIndex > -1)
            {
                frame = _BindingList[_movingFrameIndex];
            }
            RaiseSelectedFrameChanged(frame);
            // }



            Rectangle? current = GetRectangleByMouseX(e.X);

            if (current == null || !current.HasValue)
            {
                this.DataGridView.Cursor = Cursors.Default;
                return;
            }

            if (e.X > current.Value.X + current.Value.Width - 10 && e.X < current.Value.X + current.Value.Width)
            {
                _isRightSplitterClicked = true;
                //Cursor = Cursors.VSplit; 
                Point screenPoint = e;
                _initialRightSplitterScreenCoordinatesX = screenPoint.X;
                _initialWidth = current.Value.Width;
                assignWidthCount = 0;
            }
            */
        }
        protected override void OnMouseDown(DataGridViewCellMouseEventArgs e)
        {
            base.OnMouseDown(e);
            _movingFrameIndex = GetRectangleIndexByMouseX(e.X);
            _selectedFrameIndex = _movingFrameIndex;
            // if (currentMovingIndex != _movingFrameIndex)
            // {
            object frame = null;//DataGridView.Rows[e.RowIndex].DataBoundItem; 

            if (_movingFrameIndex > -1)
            {
                frame = _BindingList[_movingFrameIndex];
            }
            RaiseSelectedFrameChanged(frame);
            // }



            Rectangle? current = GetRectangleByMouseX(e.X);

            if (current == null || !current.HasValue)
            {
                this.DataGridView.Cursor = Cursors.Default;
                return;
            }

            if (e.Location.X > current.Value.X + current.Value.Width - 10 && e.Location.X < current.Value.X + current.Value.Width)
            {
                _isRightSplitterClicked = true;
                //Cursor = Cursors.VSplit; 
                Point screenPoint = e.Location;
                _initialRightSplitterScreenCoordinatesX = screenPoint.X;
                _initialWidth = current.Value.Width;
                assignWidthCount = 0;
            }

        }

        protected override void OnMouseUp(DataGridViewCellMouseEventArgs e)
        {
            base.OnMouseUp(e);
            _isRightSplitterClicked = false;
            //Cursor = Cursors.Default; 

        }

        protected override void OnKeyDown(KeyEventArgs e, int rowIndex)
        {
            base.OnKeyDown(e, rowIndex);
           

            if (e.KeyCode == Keys.Delete)
            {
                if (_selectedFrameIndex < 0 || _BindingList.Count<=0)
                    return;

                object frame2Delete = SelectedFrame;
                if (frame2Delete != null)
                {
                    _BindingList.Remove(SelectedFrame);
                    SelectPrevious();
                }
               // MessageBox.Show(_selectedFrameIndex.ToString ()); 
            
            }
            if (e.KeyCode == Keys.Left) 
            {
                SelectPrevious();
            }
            if (e.KeyCode == Keys.Right )
            {
                SelectNext ();
            }
        }

        private object SelectedFrame
        {
            get
            {
                if (_BindingList.Count < 1)
                    return null;

                if (_selectedFrameIndex < 0 || _selectedFrameIndex >= _BindingList.Count)
                    return null;

                return _BindingList[_selectedFrameIndex];
            }
        }


        private void Select(int index)
        {
            RaiseSelectedFrameChanged(SelectedFrame);

            if (index < 0 || index >= _BindingList.Count)
                return;

            _selectedFrameIndex = index;

            this.DataGridView.InvalidateCell(this);

            Selected = true;

            Debug.WriteLine(Selected.ToString() + " " + _selectedFrameIndex);

            DataGridView.Select();
            DataGridView.Focus();
            _Column.Selected = true; 
        }

        private void SelectNext()
        {
            _selectedFrameIndex += 1;
            Select(_selectedFrameIndex);
        }
        private void SelectPrevious()
        {
            _selectedFrameIndex -= 1;
            Select(_selectedFrameIndex);
        }
        private void SelectLast()
        {
            if (_BindingList.Count <= 0)
                return;
            Select(_BindingList.Count-1);
        }


        private void Add(int width)
        {
            Rectangle? last = GetLastRectangle();
            Rectangle newRect = Rectangle.Empty;
            if (last == null || !last.HasValue)
            {
                newRect = new Rectangle(Point.Empty, new Size(width, this.Size.Height));
            }
            else
            {
                newRect = new Rectangle(new Point(last.Value.X + last.Value.Width + 1, 0), new Size(width, this.Size.Height));
            }

            _rect.Add(newRect);
            //Invalidate();
        }
    }

}
